// This is unpublished source code. Michah Lerner 2006

package trieMatch.keywordMatcher;

import java.util.List;

/**
 * Implementation retrieves the <strong>LONGEST</strong> matching criterion (longest matches)
 * 
 * @author Michah.Lerner
 * 
 */
public class SortedtrieMatchLONGEST extends TrieMatcher {

	public SortedtrieMatchLONGEST() {
		super();
	}

	public SortedtrieMatchLONGEST(final Tiers tiers) { // Allocates a sequencer (thread safety)
		super(tiers);
	}

	public SortedtrieMatchLONGEST(final Tiers tiers, final Sequencer sequencer) { // Accepts a sequencer
		super(tiers, sequencer);
	}

	@Override
	List<KMDefinition> findMaxMatch(final Tiers current, final int pos) {
		if (pos >= lookingFor.size()) { return current.instances != null
				? validForMatchtype(current.instances)
				: emptyMatchable; }
		final Tiers nTier = current.successors.get(lookingFor.get(pos).getValue());
		if (nTier != null) {
			// INLINED: final List<KMDefinition> v1 = findMoreMaxMatch(nTier, pos);
			depthStack.push(pos);
			final List<KMDefinition> v1 = findMaxMatch(nTier, pos + 1);
			depthStack.pop();
			final List<KMDefinition> v2 = findMaxMatch(current, pos + 1);
			if (v1.size() == 0) { return v2; }
			if (v2.size() == 0) { return v1; }
			return (v1.get(0).score < v2.get(0).score)
					? v2
					: v1;
		}
		return findMaxMatch(current, pos + 1);
	}
}
